<template>
  <van-dialog
    v-model:show="open"
    title="地点范围"
    :showConfirmButton="true"
    :showCancelButton="false"
    destroy-on-close>
    <div id="mapDiv" style="width: 100%; height: 450px;margin-top: 10px;"></div>
  </van-dialog>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { showToast } from "vant";
// console.log(APPENV, 'APPENV')
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  isDetail: {
    type: Boolean,
    default: false
  },
  faLng: {
    type: Number,
    default: 0
  },
  faLat: {
    type: Number,
    default: 0
  },
  faXpoint: {
    type: Array,
    default: () => []
  },
  faYpoint: {
    type: Array,
    default: () => []
  },
  faZoom: {
    type: Number,
    default: 0
  }
})

const open = ref<boolean>(false)
const loading = ref<boolean>(false)
const openTool = ref<boolean>(false)
const scopePoint = ref({
  xPoint: [] as any[],
  yPoint: [] as any[],
  zoom: 0
})
const emit = defineEmits(['closeModal', 'transferScopeVal'])

// watch(
//   () => props.isOpen,
//   async (newValue) => {
//     console.log(newValue, 'newValue')
//     open.value = newValue
//     if (newValue) {
//       if (props.faXpoint?.length > 2 && props.faYpoint?.length > 2) {
//         scopePoint.value.xPoint = props.faXpoint
//         scopePoint.value.yPoint = props.faYpoint
//         scopePoint.value.zoom = props.faZoom
//         zoom.value = props.faZoom
//       }
//       await nextTick() // 等待 DOM 更新
//       initMap() // 初始化地图
//     }
//   }
// )

const reSet = () => {
  openTool.value = false
  scopePoint.value.xPoint = []
  scopePoint.value.yPoint = []
  scopePoint.value.zoom = 0
  clearAll()
}

const handleOk = () => {
  loading.value = true

  if (scopePoint.value.xPoint.length > 2 && scopePoint.value.yPoint.length > 2) {
    scopePoint.value.zoom = getMapZoom()
    emit('transferScopeVal', scopePoint.value)
    showToast('操作成功！')
    handleCancel()
  } else {
    showToast('请先进行范围划定！')
  }

  loading.value = false
}

const handleCancel = () => {
  reSet()
  emit('closeModal', false)
}

// 定义地图对象
let map: any = null
let polygonTool: any = null
const handler = ref<any>(null)
const zoom = ref(12)

// 初始化地图
const initMap = () => {
  try {
    const mapDiv = document.getElementById('mapDiv')
    if (!mapDiv) {
      throw new Error('地图容器未找到！')
    }

    map = new T.Map('mapDiv')

    const center = new T.LngLat(props.faLng, props.faLat)
    map.centerAndZoom(center, zoom.value)

    const marker = new T.Marker(center)
    map.addOverLay(marker)

    // 添加矢量地图图层
    const vectorLayer = new T.TileLayer(
      `${APPENV.VITE_TIANDITU_PROXY_T1}/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${APPENV.VITE_TIANDITU_TDKEY}`
    ) // 矢量地图
    map.addLayer(vectorLayer)

    // 添加注记图层
    const labelLayer = new T.TileLayer(
      `${APPENV.VITE_TIANDITU_PROXY_T1}/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=${APPENV.VITE_TIANDITU_TDKEY}`
    ) // 注记
    map.addLayer(labelLayer)

    const config = {
      showLabel: true,
      color: 'red',
      weight: 3,
      opacity: 0.8,
      fillColor: 'red',
      fillOpacity: 0.12
    }

    // 创建标注工具对象
    polygonTool = new T.PolygonTool(map, config)

    // 添加多边形覆盖物
    if (props.faXpoint && props.faYpoint) {
      const points = []
      for (let i = 0; i < props.faXpoint.length; i++) {
        points.push(new T.LngLat(props.faXpoint[i], props.faYpoint[i]))
      }
      //创建面对象
      const polygon = new T.Polygon(points, config)
      //向地图上添加面
      map.addOverLay(polygon)
    }
  } catch (error) {
    console.error('地图初始化失败：', error)
  }
}

// 开启多边形工具
const openPolygonTool = () => {
  if (scopePoint.value.xPoint.length > 0) clearOverlays()
  if (handler.value) handler.value.close()
  handler.value = new T.PolygonTool(map)
  handler.value.open()
  removeMapClick()
  map.addEventListener('click', MapClick)
  map.addEventListener('dblclick', MapdbClick)
  openTool.value = true
}

// 地图单击事件
const MapClick = (e: any) => {
  scopePoint.value.xPoint.push(e.lnglat.getLng())
  scopePoint.value.yPoint.push(e.lnglat.getLat())
}

// 地图双击事件
const MapdbClick = (e: any) => {
  openTool.value = false
  if (scopePoint.value.xPoint.length <= 2) {
    scopePoint.value.xPoint = []
    scopePoint.value.yPoint = []
  }
}

// 移除地图点击事件
const removeMapClick = () => {
  map.removeEventListener('click', MapClick)
  map.removeEventListener('dblclick', MapdbClick)
}

const clearOverlays = () => {
  if (map) map.clearOverLays()

  scopePoint.value.xPoint = []
  scopePoint.value.yPoint = []

  const center = new T.LngLat(props.faLng, props.faLat)
  map.centerAndZoom(center, zoom.value)
  const marker = new T.Marker(center)
  map.addOverLay(marker)
}

// 获取当前地图缩放级别
const getMapZoom = () => {
  return map.getZoom()
}

// 清空地图
const clearAll = () => {
  map.clearOverLays()
  polygonTool = null
  handler.value = null
}

const opendialog = async() => {
  open.value = true
  if (props.faXpoint?.length > 2 && props.faYpoint?.length > 2) {
    scopePoint.value.xPoint = props.faXpoint
    scopePoint.value.yPoint = props.faYpoint
    scopePoint.value.zoom = props.faZoom
    zoom.value = props.faZoom
  }
  await nextTick() // 等待 DOM 更新
  initMap() // 初始化地图
}

defineExpose({
  opendialog
})
</script>

<style lang="less" scoped>
.modal-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  .btn-width {
    width: 160px;
  }
}
.operate-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f2f2f2;
  padding: 6px 8px;
  border-radius: 5px;
  margin-bottom: 12px;
}
</style>
